import { createRequire } from 'node:module';
import process from 'node:process';

import * as modules from './modules/index.mjs';
import {
  APP_PATH,
  createFolder,
  DEBUG_PATH,
  LOG_PATH,
  PROJ_PATH,
  UPLOAD_PATH,
} from './utils/index.mjs';

const require = createRequire(import.meta.url);

const dayjs = require('dayjs');
const express = require('express');
const expressWs = require('express-ws');
const pino = require('pino');
const rfs = require('rotating-file-stream');

const TERMINAL_PORT = 4000;

const app = express();

// 创建多个流
const streams = [
  {
    hooks: {
      logMethod(inputArgs, method) {
        if (inputArgs.length === 2 && inputArgs[0].msg) {
          inputArgs[0].originalMsg = inputArgs[0].msg;
        }
        return method.apply(this, inputArgs);
      },
    },
    level: 'debug',
    stream: process.stdout,
  },
  { level: 'error', stream: process.stderr },
  { level: 'fatal', stream: process.stderr },
  {
    stream: rfs.createStream(`web os-${dayjs().format('YYYY-MM-DD')}.log`, {
      compress: 'gzip', // 压缩旧日志文件
      interval: '1d', // 每天轮转一次
      path: LOG_PATH, // 日志文件存放路径
      size: '10M', // 每个日志文件的最大大小
    }),
  },
];

const logger = pino({}, pino.multistream(streams));

expressWs(app);

// 设置允许跨域访问该服务.
app.all('*', (req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  // Access-Control-Allow-Headers ,可根据浏览器的F12查看,把对应的粘贴在这里就行
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Methods', '*');
  res.header('Content-Type', 'application/json;charset=utf-8');
  next();
});

// =================终端============================
modules.default.createTeminalHandler(app, logger);

// =================网络============================
modules.default.createNetworkHandler(app, logger);

// =================设计============================
modules.default.createDesignHandler(app, logger);

// =================文件夹============================
modules.default.createFolderHandler(app, logger);

// =================文件============================
modules.default.createFileHandler(app, logger);

// =================调试环境============================
modules.default.createDebugHandler(app, logger);

// =================桌面图标============================
modules.default.createAppHandler(app, logger);

// =================系统信息============================
modules.default.createOsHandler(app, logger);

// const ip4v = getLocalIPv(4);

// logger.info(`App listening to http://${ip4v}:${TERMINAL_PORT}`);
// app.listen(TERMINAL_PORT, ip4v);
app.listen(TERMINAL_PORT);
logger.info(`wss linsting on 端口 ${TERMINAL_PORT}`);

// 初始化文件夹
const initDirs = [
  LOG_PATH,
  PROJ_PATH,
  DEBUG_PATH,
  UPLOAD_PATH,
  APP_PATH,
];
initDirs.forEach((dir) => {
  createFolder(dir);
});
